import {
  Body,
  Controller,
  Delete,
  Get,
  InternalServerErrorException,
  Param,
  Patch,
  Post,
  Query,
  Req,
} from '@nestjs/common'
import { ApiBearerAuth, ApiBody, ApiOperation, ApiParam, ApiTags } from '@nestjs/swagger'
import * as Config from 'config'
import { PagenationPipe } from '@/pipes/pagenation.pipe'
import { QueryEmptyTrimPipe } from '@/pipes/queryEmptyTrim.pipe'
import { CreateRoleDto } from './dto/create-role.dto'
import { GetRoleDto } from './dto/get-role.dto'
import { UpdateRoleDto } from './dto/update-role.dto'
import { RolesService } from './roles.service'

@Controller('systemManage')
@ApiBearerAuth()
@ApiTags('角色模块')
export class RolesController {
  constructor(private readonly rolesService: RolesService) {}

  @Post('createRole')
  @ApiOperation({ summary: '创建角色' })
  @ApiBody({ type: CreateRoleDto })
  create(@Body() createRoleDto: CreateRoleDto) {
    return this.rolesService.create(createRoleDto)
  }

  @Get('getRoleList')
  @ApiOperation({ summary: '角色列表' })
  findAll(@Query(PagenationPipe, QueryEmptyTrimPipe) getRoleDto: GetRoleDto) {
    console.log('getRoleDto', getRoleDto)
    return this.rolesService.findAllAndCount(getRoleDto)
  }

  @Get('getAllRoles')
  @ApiOperation({ summary: '获取所有角色' })
  async getAllRoles() {
    const result = await this.rolesService.findAll(
      {},
      {
        select: ['id', 'roleCode', 'roleName'],
      }
    )
    return result.filter((item) => item.roleCode !== Config.get('role').superAdminCode)
  }

  @Get('getRole/:id')
  @ApiOperation({ summary: '获取角色详情' })
  @ApiParam({ name: 'id', description: '角色id' })
  async findOne(@Param('id') id: string) {
    const role = await this.rolesService.findOne(id, {
      relations: ['menus', 'permissions'],
    })
    return {
      ...role,
      menus: role.menus.map((menu) => menu.id),
      permissions: role.permissions.map((permission) => permission.id),
    }
  }

  @Get('getCheckedMenuByRole/:id')
  @ApiOperation({ summary: '获取角色拥有的菜单id集合' })
  @ApiParam({ name: 'id', description: '角色id' })
  async getCheckedMenuByRole(@Param('id') id: string) {
    const role = await this.rolesService.findOne(id, {
      relations: ['menus'],
    })
    return role.menus.map((menu) => menu.id)
  }

  @Get('getCheckedButtonByRole/:id')
  @ApiOperation({ summary: '根据角色获取该角色拥有的所有按钮权限' })
  @ApiParam({ name: 'id', description: '角色id' })
  async getCheckedButtonByRole(@Param('id') id: string) {
    const role = await this.rolesService.findOne(id, {
      relations: ['permissions'],
    })
    return role.permissions.map((permission) => permission.id)
  }

  @Patch('updateRole/:id')
  @ApiOperation({ summary: '编辑角色' })
  @ApiParam({ name: 'id', description: '角色id' })
  @ApiBody({ type: UpdateRoleDto })
  async update(
    @Req() req: ReqPayload,
    @Param('id') id: string,
    @Body() updateRoleDto: UpdateRoleDto
  ) {
    const role = await this.rolesService.update(id, updateRoleDto, req.user)
    return {
      ...role,
      // menus: role.menus?.map((menu) => menu.id) || [],
      // permissions: role.permissions?.map((permission) => permission.id) || [],
    }
  }

  @Delete('deleteRole/:ids')
  @ApiOperation({ summary: '删除角色' })
  @ApiParam({ name: 'ids', description: '角色ids' })
  async remove(@Param('ids') ids: string) {
    const deleteIds = ids.split(',').map((id) => id)
    for (const id of deleteIds) {
      if (id === Config.get('role').superAdminId) {
        throw new InternalServerErrorException('超级管理员角色不可删除')
      }
      const roleUsers = await this.rolesService.findOne(id, {
        relations: ['users', 'users.user'],
      })
      if (roleUsers.users?.length) {
        throw new InternalServerErrorException(
          `${roleUsers.roleCode}已经被用户${roleUsers.users[0].user.userName}等绑定，请解绑后再删除`
        )
      }
    }
    return this.rolesService.remove(deleteIds)
  }
}
